local extension = Package("sktanlang")
extension.extensionName = "jilvRem"

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["sktanlang"] = "极略三国-贪狼",
}

local dongbai = General(extension, "sk__dongbai", "qun", 3, 3, General.Female)
local sk__shemi = fk.CreateTriggerSkill{
  name = "sk__shemi",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart, fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and player.phase == Player.Discard then
      if event == fk.EventPhaseStart then
        return not player:isKongcheng()
      else
        return player:getMark("sk__shemi_invoke-phase") > 0
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      local n = player:getHandcardNum() - player:getMaxCards()
      room:askForDiscard(player, math.max(n, 0), player:getHandcardNum(), false, self.name, false, ".",
        "#sk__shemi:::"..math.max(n, 0)..":"..player:getMark(self.name))
    else
      player:broadcastSkillInvoke(self.name)
      room:notifySkillInvoked(player, self.name, "special")
      room:addPlayerMark(player, MarkEnum.SkDrawNCards, 1)
      if not player:isWounded() then
        room:changeMaxHp(player, 1)
      end
    end
  end,

  refresh_events = {fk.EventAcquireSkill, fk.EventPhaseEnd},
  can_refresh = function (self, event, target, player, data)
    if target == player then
      if event == fk.EventAcquireSkill then
        return data == self
      else
        return player:hasSkill(self, true) and player.phase == Player.Discard
      end
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if event == fk.EventAcquireSkill then
      local id, end_id = 1, 1
      room.logic:getEventsByRule(GameEvent.Phase, 1, function (e)
        if e.data[1] == player and e.data[2] == Player.Discard then
          id, end_id = e.id, e.end_id
          return true
        end
      end, 1)
      if id > 1 then
        local n = 0
        room.logic:getEventsByRule(GameEvent.MoveCards, 1, function (e)
          if e.id <= end_id then
            for _, move in ipairs(e.data) do
              if move.from == player.id and move.moveReason == fk.ReasonDiscard and move.toArea == Card.DiscardPile then
                n = n + #move.moveInfo
              end
            end
          end
        end, id)
        room:setPlayerMark(player, self.name, n)
      end
    else
      local n = 0
      room.logic:getEventsByRule(GameEvent.MoveCards, 1, function (e)
        for _, move in ipairs(e.data) do
          if move.from == player.id and move.moveReason == fk.ReasonDiscard and move.toArea == Card.DiscardPile then
            n = n + #move.moveInfo
          end
        end
        return false
      end, room.logic:getCurrentEvent():findParent(GameEvent.Phase, true).id)
      if n > player:getMark(self.name) then
        room:setPlayerMark(player, "sk__shemi_invoke-phase", 1)
      end
      room:setPlayerMark(player, self.name, n)
    end
  end,
}
local sk__jiaohui = fk.CreateTriggerSkill{
  name = "sk__jiaohui",
  anim_type = "defensive",
  events = {fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_cost = function(self, event, target, player, data)
    local extra_data = {
      num = 1,
      min_num = 0,
      include_equip = true,
      skillName = self.name,
      pattern = ".",
    }
    local success, dat = player.room:askForUseActiveSkill(player, "discard_skill", "#sk__jiaohui-invoke", true, extra_data)
    if success then
      self.cost_data = dat.cards or {}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    if #self.cost_data == 0 then
      player:drawCards(1, self.name)
    else
      player.room:throwCard(self.cost_data, self.name, player, player)
    end
    if player:getHandcardNum() == player.hp then
      data.damage = data.damage - 1
    end
  end,
}
dongbai:addSkill(sk__shemi)
dongbai:addSkill(sk__jiaohui)
Fk:loadTranslationTable{
  ["sk__dongbai"] = "董白",
  ["#sk__dongbai"] = "",

  ["sk__shemi"] = "奢靡",
  [":sk__shemi"] = "锁定技，弃牌阶段，你可以多弃置任意张手牌；弃牌阶段结束时，若你于此阶段内弃置的牌数大于你的上一个弃牌阶段，"..
  "你的摸牌阶段摸牌数+1，然后若你未受伤，你加1点体力上限。",
  ["sk__jiaohui"] = "狡慧",
  [":sk__jiaohui"] = "当你受到伤害时，你可以摸一张牌或弃置一张牌，然后若你的手牌数等于体力值，此伤害-1。",
  ["#sk__shemi"] = "请弃置至少 %arg 张牌（你上个弃牌阶段弃置了%arg2张，若多弃置则可以触发“奢靡”）",
  ["#sk__jiaohui-invoke"] = "狡慧：摸一张牌或弃一张牌，然后若手牌数等于体力值，此伤害-1",

  ["$sk__shemi1"] = "这些东西，本小姐看不上呢。",
  ["$sk__shemi2"] = "本小姐给你的，你敢拿么？",
  ["$sk__jiaohui1"] = "若是伤了本小姐，可是要株连九族！",
  ["$sk__jiaohui2"] = "哼，你这点小心思，可瞒不过本小姐。",
  ["~sk__dongbai"] = "爷爷……",
}

local xushi = General(extension, "sk__xushi", "wu", 3, 3, General.Female)
local sk__wengua = fk.CreateTriggerSkill{
  name = "sk__wengua",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target.phase == Player.Start and not target.dead and not target:isNude()
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local prompt = "#sk__wengua-give:"..player.id
    if target == player then
      prompt = "#sk__wengua-draw::"..target.id
    end
    local card = room:askForCard(target, 1, 1, true, self.name, true, ".", prompt)
    if #card > 0 then
      self.cost_data = card
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if target ~= player then
      room:moveCardTo(self.cost_data, Card.PlayerHand, player, fk.ReasonGive, self.name, nil, false, target.id)
    end
    if player.dead or player:isNude() then return end
    local card
    if target == player then
      card = self.cost_data
    else
      card = room:askForCard(player, 1, 1, true, self.name, true, ".", "#sk__wengua-draw::"..target.id)
    end
    if #card > 0 then
      room:moveCards({
        ids = card,
        from = player.id,
        toArea = Card.DrawPile,
        moveReason = fk.ReasonPut,
        skillName = self.name,
        drawPilePosition = -1,
      })
      if not player.dead then
        player:drawCards(1, self.name)
      end
      if not target.dead then
        target:drawCards(1, self.name)
      end
    end
  end,
}
local sk__fuzhu = fk.CreateActiveSkill{
  name = "sk__fuzhu",
  anim_type = "offensive",
  frequency = Skill.Limited,
  card_num = 0,
  target_num = 1,
  prompt = "#sk__fuzhu",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  target_filter =function (self, to_select, selected, selected_cards, card, extra_data, player)
    return #selected == 0 and to_select ~= player.id
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    while not player.dead and not target.dead do
      local id = room:getNCards(1, "bottom")[1]
      room:moveCardTo(id, Card.Processing, nil, fk.ReasonJustMove, self.name, nil, true, player.id)
      room:delay(800)
      if Fk:getCardById(id).color == Card.Black then
        local card = Fk:cloneCard("slash")
        card:addSubcard(id)
        card.skillName = self.name
        if not player:isProhibited(target, card) then
          room:useVirtualCard("slash", {id}, player, target, self.name, true)
        else
          break
        end
      else
        room:moveCardTo(id, Card.DiscardPile, nil, fk.ReasonJustMove, self.name, nil, true, player.id)
        break
      end
    end
  end,
}
xushi:addSkill(sk__wengua)
xushi:addSkill(sk__fuzhu)
Fk:loadTranslationTable{
  ["sk__xushi"] = "徐氏",
  ["#sk__xushi"] = "",

  ["sk__wengua"] = "问卦",
  [":sk__wengua"] = "一名角色的准备阶段，其可以交给你一张牌，然后你可以将一张牌置于牌堆底，与其各摸一张牌。",
  ["sk__fuzhu"] = "伏诛",
  [":sk__fuzhu"] = "限定技，出牌阶段，你可以选择一名其他角色，重复流程：展示牌堆底牌，若此牌为黑色，你将此牌当【杀】对其使用。",
  ["#sk__wengua-give"] = "问卦：你可以交给 %src 一张牌，其可以将一张牌置于牌堆底，与你各摸一张牌",
  ["#sk__wengua-draw"] = "问卦：是否将一张牌置于牌堆底，与 %dest 各摸一张牌？",
  ["#sk__fuzhu"] = "伏诛：将牌堆底所有黑色牌当【杀】对一名角色使用！",

  ["$sk__wengua1"] = "阴阳相生，祸福相伴。",
  ["$sk__wengua2"] = "趋吉避害，不可逆天而为。",
  ["$sk__fuzhu1"] = "你的死期终于到了！",
  ["$sk__fuzhu2"] = "还我夫君命来！",
  ["~sk__xushi"] = "恨不能报……弑君之仇……",
}

local wuyi = General(extension, "sk__wuyi", "shu", 4)
Fk:addQmlMark{
  name = "sk__zhidi",
  how_to_show = function(name, value)
    if type(value) == "table" then
      return tostring(#value)
    end
    return " "
  end,
  qml_path = "packages/jilvRem/qml/ZhidiBox"
}
local sk__zhidi = fk.CreateTriggerSkill{
  name = "sk__zhidi",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start and
      player:usedSkillTimes(self.name, Player.HistoryGame) < 4
  end,
  on_use = function(self, event, target, player, data)
    math.randomseed(tonumber(tostring(os.time()):reverse():sub(1, 6)))
    local mark = player:getTableMark("@[sk__zhidi]")
    local choices = {}
    for i = 1, 4, 1 do
      if not table.contains(mark, "sk__zhidi"..i) then
        table.insert(choices, "sk__zhidi"..i)
      end
    end
    table.insert(mark, table.random(choices))
    player.room:setPlayerMark(player, "@[sk__zhidi]", mark)
  end,
}
local sk__zhidi_delay = fk.CreateTriggerSkill{
  name = "#sk__zhidi_delay",
  mute = true,
  events = {fk.Damage, fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    if target and target == player and data.card and data.card.trueName == "slash" then
      if event == fk.Damage then
        return table.contains(player:getTableMark("@[sk__zhidi]"), "sk__zhidi1")
      elseif event == fk.TargetSpecified then
        return table.contains(player:getTableMark("@[sk__zhidi]"), "sk__zhidi2")
      end
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke("sk__zhidi")
    room:notifySkillInvoked(player, "sk__zhidi", "offensive")
    if event == fk.Damage then
      player:drawCards(1, "sk__zhidi")
    elseif event == fk.TargetSpecified then
      data.unoffsetableList = table.map(room.alive_players, Util.IdMapper)
      local to = room:getPlayerById(data.to)
      local use_event = room.logic:getCurrentEvent():findParent(GameEvent.UseCard, true)
      if use_event == nil then return end
      room:addPlayerMark(to, fk.MarkArmorNullified)
      use_event:addCleaner(function()
        room:removePlayerMark(to, fk.MarkArmorNullified)
      end)
    end
  end,
}
local sk__zhidi_targetmod = fk.CreateTargetModSkill{
  name = "#sk__zhidi_targetmod",
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and table.contains(player:getTableMark("@[sk__zhidi]"), "sk__zhidi3") and
      scope == Player.HistoryPhase then
      return player:usedSkillTimes("sk__zhidi", Player.HistoryGame)
    end
  end,
  bypass_distances =  function(self, player, skill)
    return skill.trueName == "slash_skill" and table.contains(player:getTableMark("@[sk__zhidi]"), "sk__zhidi3")
  end,
  extra_target_func = function(self, player, skill)
    if skill.trueName == "slash_skill" and table.contains(player:getTableMark("@[sk__zhidi]"), "sk__zhidi4") then
      return player:usedSkillTimes("sk__zhidi", Player.HistoryGame)
    end
  end,
}
sk__zhidi:addRelatedSkill(sk__zhidi_delay)
sk__zhidi:addRelatedSkill(sk__zhidi_targetmod)
wuyi:addSkill(sk__zhidi)
Fk:loadTranslationTable{
  ["sk__wuyi"] = "吴懿",
  ["#sk__wuyi"] = "",

  ["sk__zhidi"] = "制敌",
  [":sk__zhidi"] = "锁定技，准备阶段，你随机获得以下效果中未获得过的一项：<br>1.当你使用【杀】造成伤害后，你摸一张牌；<br>2.你使用【杀】"..
  "无视防具且不能被【闪】响应；<br>3.你使用【杀】无距离限制，且出牌阶段使用【杀】次数上限+X；<br>4.你使用【杀】的目标上限+X。<br>"..
  "（X为此技能发动的次数）",
  ["@[sk__zhidi]"] = "制敌",
  ["sk__zhidi1"] = "使用【杀】造成伤害后，你摸一张牌。",
  ["sk__zhidi2"] = "你使用【杀】无视防具且不能被【闪】响应。",
  ["sk__zhidi3"] = "你使用【杀】无距离限制，出牌阶段使用【杀】次数上限增加。",
  ["sk__zhidi4"] = "使用【杀】的目标上限增加。",
  ["#sk__zhidi_delay"] = "制敌",

  ["$sk__zhidi1"] = "以柔制刚，以弱制强！",
  ["$sk__zhidi2"] = "柔不可卷，刚不可折！",
  ["~sk__wuyi"] = "北伐还未成……",
}

return extension
